<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import KoDataItem from "@/views/domain/kubeHud/views/components/ko-data-item/index.vue";
import { objectToList } from "../../../utils";

type Prop = {
  readonly?: boolean;
  editable?: boolean;
  disabledKeys?: string[];
};

type ListRow = {
  key: string;
  originKey: string;
  value: any;
};

const props = defineProps<Prop>();

const kvModel = defineModel<Record<string, any>>();
const tableKey = ref("");

const editItems = ref<ListRow[]>([]);

const reloadItems = () => {
  editItems.value = (objectToList(kvModel.value) as ListRow[]).sort();
  editItems.value.forEach(item => {
    item.originKey = `${item.key}`;
  });
  tableKey.value = `${new Date().getTime()}`;
};

const rowOperatorDisable = (item: ListRow) => {
  return props.readonly || props.disabledKeys?.includes(item.key);
};

const onKeyChanged = (item: ListRow) => {
  console.log(`onKeyChanged ${item.key}`);
  if (item.originKey !== item.key) {
    delete kvModel.value[item.originKey];
    kvModel.value[item.key] = item.value;
    item.originKey = `${item.key}`;
  }
};

const onValueChanged = (item: ListRow) => {
  kvModel.value[item.key] = item.value;
};

const onDelete = (row: ListRow) => {
  const itemIndex = editItems.value.findIndex(item => item.key === row.key);
  if (itemIndex >= 0) {
    editItems.value.splice(itemIndex, 1);
    delete kvModel.value[row.key];
  }
};

watch(
  () => kvModel.value,
  () => {
    reloadItems();
  },
  { deep: true }
);

onMounted(() => {
  reloadItems();
});
</script>

<template>
  <table :key="tableKey" class="w-full">
    <tr
      v-for="(row, index) in editItems"
      :key="`${tableKey}_${index}`"
      class="table-row"
    >
      <td width="48%">
        <ko-data-item
          v-model="row.key"
          :disabled="rowOperatorDisable(row)"
          placeholder="key"
          clearable
          itemType="input"
          @change="() => onKeyChanged(row)"
        />
      </td>
      <td width="48%">
        <ko-data-item
          v-model="row.value"
          :disabled="rowOperatorDisable(row)"
          clearable
          itemType="input"
          placeholder="value"
          @change="() => onValueChanged(row)"
        />
      </td>
      <td v-if="editable" width="4%">
        <el-button
          link
          type="danger"
          :disabled="rowOperatorDisable(row)"
          icon="Delete"
          @click="onDelete(row)"
        />
      </td>
    </tr>
  </table>
</template>
<style lang="scss" scoped>
.table-row {
  td {
    padding: 0 5px;
  }
}
</style>
